import {httpServer} from '@/config/server.js';
const noLoginApi = [
	'/api/User/login',
	'/addons/shop/api.common/get_agreement_info',
	'/addons/shop/api.login/login',
	'/addons/shop/api.common/get_index_info',
	'/addons/shop/api.common/get_index_content', //根据轮播获取富文本
	'/addons/shop/api.goods/get_category_list',
	
	'/addons/shop/api.goods/get_goods_info',
]
let config = {
	baseURL: httpServer,
	getToken(resolve, reject) {
		let token = uni.getStorageSync('token');
		return token || ''
	},
	// 请求拦截器
	beforeRequest(options = {}) {
		return new Promise((resolve, reject) => {
			// #ifdef APP-PLUS
			//避免https拦截
			options.sslVerify = false
			// #endif
			let token = this.getToken()
			options.header = {
				"token": token
			}
			if(!noLoginApi.includes(options.url) && !token){
				//请求携带登录标识
				reject()
				uni.navigateTo({
					url:'/pages/login/index'
				})
				return
			}
			options.url = this.baseURL + options.url;
			options.method = options.method || 'POST';
			
			resolve(options)
		})
	},
	// 响应拦截器
	handleResponse(data) {
		return new Promise((resolve, reject) => {
			const [err, res] = data;
			if (res && res.statusCode === 401) {
				let msg = res.data.msg || '请登录后再操作';
				uni.showToast({
					icon: 'none',
					title: msg
				})
				uni.clearStorageSync()
				return reject(msg)
			}
			if (res && res.statusCode !== 200) {
				let msg = res.data.msg || '请求错误';
				uni.showToast({
					icon: 'none',
					title: msg
				})
				return reject(msg)
			}
			if (err) {
				uni.showToast({
					icon: 'none',
					title: '请求错误'
				})
				return reject(err)
			}
			if(res && res.statusCode === 200 && res.data.code == 1){
				return resolve(res.data)
			}else{
				uni.showToast({
					title:res.data.msg,
					icon:'none'
				})
				return reject(res.data.msg)
			}
		})
	},
}

let request = (options = {}) => {
	return config.beforeRequest(options).then(opt => {
		return uni.request(opt)
	}).then(res => config.handleResponse(res))
}
export default request
